// components/indexItem/indexItem.js
const app = getApp()
import handler from '../../utils/dataHander'
import dataUtils from '../../utils/getDataUtil'
Component({
  /**
   * 组件的属性列表
   */
  properties: {},

  /**
   * 组件的初始数据
   */
  /**
   * 页面数据源
   */
  data: {
    subject: [], //表示当前选中什么科目
    index: 0, //表示当前科目的索引
    // learnType: ["顺序练习", "随机练习", "收藏练习", "错题练习", "开始考试",  "考卷回顾", "英语听力","英语阅读","暂无更多"],
    learnType: [{
        type: "顺序练习",
        image: "../../images/书本16.png"
      },
      {
        type: "随机练习",
        image: "../../images/随机.png"
      },
      {
        type: "收藏练习",
        image: "../../images/收藏夹空空如也.png"
      },
      {
        type: "错题练习",
        image: "../../images/错误.png"
      },
      {
        type: "开始考试",
        image: "../../images/考试.png"
      },
      {
        type: "考卷回顾",
        image: "../../images/发布测试DFaaS.png"
      },
      {
        type: "英语听力",
        image: "../../images/收音机.png"
      },
      {
        type: "英语阅读",
        image: "../../images/暂无阅读.png"
      },
      {
        type: "暂无更多",
        image: "../../images/更多.png"
      },
    ],
    gradientColor: {
      '0%': '#ffd01e',
      '100%': '#99FFFF',
    },
    value: 0,
    show: false
  },
  /**
   * 组件的方法列表
   */
  methods: {
    onClickHide: function () {
      this.setData({
        show: false
      });
    },
    bindPickerChange: async function (e) {
      this.setData({
        index: e.detail.value
      })
      //将用户正在学习的科目记录下来，方便下次进入不用重新选
      wx.setStorageSync('selectLibIndex', e.detail.value)
    },
    bindSearch: async function (e) {
      this.setData({
        show: true
      })
      let res = await dataUtils.searchTitle(e.detail, this.data.subject[this.data.index])
      if (res.length == 0) {
        wx.showToast({
          icon: "error",
          title: '没有找到!',
        })
        this.setData({
          show: false
        })
        return
      }
      //跳转到顺序练习页面
      app.globalData.ButtomFlag = false
      app.globalData.learnType = "随机练习"
      app.globalData.practiceFlag = false
      wx.setStorageSync('subject', res)
      this.setData({
        show: false
      })
      wx.navigateTo({
        url: '../../pages/sub/learns/learn',
      })
    },
    bindtapHandler: async function (e) {
      this.setData({
        show: true
      })
      let userInfo = wx.getStorageSync('user')
      if (!userInfo) {
        wx.showToast({
          icon: "error",
          title: '请先登录',
        })
      } else {
        //考试时间和考试条目数应该放到缓存中，缓存中查不到再去数据库中查询
        let testItem = wx.getStorageSync('testItem')
        if (!testItem) {
          this.getTestItem(e.currentTarget.id)
        }
        this.getTestItem()
        this.gotoLearn(e.target.id, this.data.subject[this.data.index])
      }
    },

    gotoLearn: async function (flag, selectLib) {
      console.log(flag, selectLib)
      app.globalData.learnType = flag
      app.globalData.selectLib = selectLib
      //进行数据库注册的异步函数    
      let item = wx.getStorageSync('user')
      let info = wx.getStorageSync(item.account)
      let lib = selectLib.toString()
      //如果缓存中没有信息， 重新去数据库确认有无注册过一次，避免每次都去数据库查询
      if (!info || (info && !info.includes(lib))) {
        let res = await this.registed(item, lib, info)
        console.log(res)
      }
      app.globalData.practiceFlag = false
      app.globalData.ButtomFlag = false
      if (flag === "随机练习") {
        // 如果是随机练习，这里要将题库顺序打乱
        await handler.randomPromise(selectLib)
        wx.navigateTo({
          url: '../../pages/sub/learns/learn',
        })
      } else if (flag === "顺序练习") {
        //否则不将题库打乱，直接进入练习页面
        //在这里在数据库中查询到相应题库的题目
        let res = await wx.cloud.database().collection("shuati").where({
          name: selectLib
        }).get()
        wx.setStorageSync('subject', res.data[0].title)
        wx.navigateTo({
          url: '../../pages/sub/learns/learn',
        })
      } else if (flag === "错题练习") {
        let res = await wx.cloud.callFunction({
          name: 'test',
          data: {
            account: item.account,
            selectLib: selectLib
          }
        })
        console.log("进入云函数进行计算", res.errMsg)
        if (res.result == "没有错题") {
          wx.showToast({
            icon: "success",
            title: res.result,
          })
        } else {
          //将题目设置到缓存中
          wx.setStorageSync('subject', res.result)
          wx.navigateTo({
            url: '../../pages/sub/learns/learn',
          })
        }
      } else if (flag === "收藏练习") {
        //进入收藏练习页面
        // 从数据库中查到收藏的题库
        wx.cloud.callFunction({
          name: 'getFav',
          data: {
            account: item.account,
            selectLib: selectLib
          }
        }).then(res => {
          console.log("进入云函数进行计算", res.errMsg)
          if (res.result.length < 1) {
            wx.showToast({
              icon: "error",
              title: "没有收藏过",
            })
          } else {
            //将题目设置到缓存中
            wx.setStorageSync('subject', res.result)
            wx.navigateTo({
              url: '../../pages/sub/learns/learn',
            })
          }
        })
      } else if (flag === "考卷回顾") {
        wx.navigateTo({
          url: '../../pages/sub/records/records',
        })
      } else if (flag === "开始考试") {
        app.globalData.ButtomFlag = true
        handler.randomTestPromise().then(res => {
          wx.navigateTo({
            url: '../../pages/sub/tests/test',
          })
        })
      } else {
        wx.showToast({
          icon: "error",
          title: '开发中',
          duration: 1500
        })
      }
      this.setData({
        show: false
      })
    },

    getTestItem: async function () {
      let item = await wx.cloud.database().collection("testItem").where({
        name: "testItem"
      }).get()
      wx.setStorageSync('testItem', item.data[0].data)
    },

    registed: async function (item, lib, info) {
      /**
       * 点击gotolearn，注册
       * 1.userRecord
       * 2.将其放入缓存中
       * 3.以后直接查询缓存，如果缓存中没有相关信息，再去数据库查找，减少数据库查找次数
       */
      let info1 = await this.registerUser(item)
      if (info1 == "collection.get:ok" || info1 == "collection.add:ok") {
        //将用户注册信息放到缓存中
        if (info) { //如果缓存里原来有数据，使用push方法
          info.push(lib)
        } else {
          info = new Array()
          info.push(lib)
        }
        //对info去重
        info = await handler.unique(info)
        wx.setStorage({
          key: item.account,
          data: info
        })
      }
      return info1
    },

    registerUser: async function (item) {
      //注册userRecord,只有顺序练习才需要注册userRecord
      let res = await wx.cloud.database().collection("userRecord").where({
        account: item.account,
        selectLib: app.globalData.selectLib
      }).get()
      if (res.data.length < 1) { //说明没查到数据，说明用户没有收藏过题目，进行添加
        let res1 = await wx.cloud.database().collection("userRecord").add({
          data: {
            account: item.account,
            selectLib: app.globalData.selectLib,
          }
        })
        return res1.errMsg
      }
      return res.errMsg
    },

  },
  lifetimes: {
    attached: async function () {
      let index = 0
      if (wx.getStorageSync('selectLibIndex')) {
        index = wx.getStorageSync('selectLibIndex')
      }
      wx.cloud.database().collection('lunbo-image').where({
        name: "lunbo"
      }).get().then(res => {
        this.setData({
          swiperList: res.data[0].lunbo,
          airplane: res.data[0].airplane,
          index: index
        })
      })
      let res = await wx.cloud.database().collection("shuati").where({
        name: "kemu"
      }).get()
      this.setData({
        subject: res.data[0].subject
      })
      console.log(this.data.subject)
    },
    ready:function(){
     
    }
  }
})